package com.mysoft.gfyx.common.concurrency.impl;

import com.alibaba.fastjson.JSON;
import com.mysoft.framework.common.exception.BusinessLogicException;
import com.mysoft.gfyx.common.concurrency.CacheLockService;
import com.mysoft.gfyx.common.util.SerializationUtil;
import org.bouncycastle.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;

@Service
public class CacheLockServiceImpl implements CacheLockService {

    @Autowired
    private Environment environment;

    private static JedisPool jedisPool;

    @PostConstruct
    public void init () {
        System.out.println("初始化Jedis池子……");
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(300);
        poolConfig.setMaxWaitMillis(2000);

        String point = environment.getProperty("SaaSConfig.cache.redisServersIp");
        String[] pointData = Strings.split(point, ':');
        String password = environment.getProperty("SaaSConfig.cache.redisServersPw");

        if (password == "") password = null;
        jedisPool = new JedisPool(poolConfig, pointData[0], Integer.valueOf(pointData[1]), 2000, password, 2);

        System.out.println("初始化Jedis池子完毕！");
    }

    public boolean getCacheLock(String key, String requestId) {
        System.out.println("获取Jedis链接……");
        Jedis jedis = jedisPool.getResource();
        long nx;
        try {
            String lockKey = CacheLockService.CLOCK_PREFIX + ":" + key;
            nx = jedis.setnx(lockKey, requestId);
            if (nx > 0) {
                System.out.println("获取锁成功……Key" + lockKey + ",RequestId:" + requestId);
                jedis.expire(lockKey, 30);
            } else {
                System.out.println("获取锁失败……Key" + lockKey + ",RequestId:" + requestId);
            }

            // System.out.println("nx:" + nx + ",nx > 0:" + (nx > 0));
        } catch (Exception e) {
            jedis.close();
            throw new BusinessLogicException(e.getMessage());
        }

        jedis.close();
        return nx > 0;
    }

    public void releaseCacheLock(String key, String requestId) {
        System.out.println("获取Jedis链接……");
        Jedis jedis = jedisPool.getResource();

        try {
            String lockKey = CacheLockService.CLOCK_PREFIX + ":" + key;
            String req = jedis.get(lockKey);
            if (req != null && req.equals(requestId)) {
                jedis.del(lockKey);
            }
        } catch (Exception e) {
            jedis.close();
            throw new BusinessLogicException(e.toString());
        }

        jedis.close();
    }

    public <T> void set(String key, T value) {
        this.set(key, value, 7200);
    }

    public <T> void set(String key, T value, long timeout) {
        System.out.println("获取Jedis链接……");
        Jedis jedis = jedisPool.getResource();
        byte[] bytesContent;

        try {
            String lockKey = CacheLockService.GLOBAL_PREFIX + ":" + key;
            bytesContent = SerializationUtil.serialize(value);
            jedis.set(lockKey.getBytes(), bytesContent);
            jedis.expire(lockKey, (int) timeout);
        } catch (Exception e) {
            jedis.close();
            throw new BusinessLogicException(e.getMessage());
        }

        jedis.close();
    }

    public <T> T get(String key) {
        System.out.println("获取Jedis链接……");
        Jedis jedis = jedisPool.getResource();
        byte[] content;

        try {
            String lockKey = CacheLockService.GLOBAL_PREFIX + ":" + key;
            content = jedis.get(lockKey.getBytes());
        } catch (Exception e) {
            jedis.close();
            throw new BusinessLogicException(e.getMessage());
        }

        jedis.close();

        return (T) SerializationUtil.deserialize(content);
    }

    public void delete(String key) {
        System.out.println("获取Jedis链接……");
        Jedis jedis = jedisPool.getResource();

        try {
            String lockKey = CacheLockService.GLOBAL_PREFIX + ":" + key;
            jedis.del(lockKey.getBytes());
        } catch (Exception e) {
            jedis.close();
            throw new BusinessLogicException(e.getMessage());
        }

        jedis.close();
    }
}
